package com.da.web.school_student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.da.web.school_student.entity.SchoolStudent;
import com.da.web.school_student.entity.StuParm;
import com.da.web.school_student.mapper.SchoolStudentMapper;
import com.da.web.school_student.service.SchoolStudentService;
import com.da.web.stu_role.entity.StuRole;
import com.da.web.stu_role.service.StuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author da
 * @time 2023/12/6 下午 3:00
 */
@Service
public class SchoolStudentServiceImpl extends ServiceImpl<SchoolStudentMapper, SchoolStudent> implements SchoolStudentService {
    @Autowired
    private StuRoleService stuRoleService;

    @Override
    public SchoolStudent getStuById(Long stuId) {
        return this.baseMapper.getStuById(stuId);
    }

    @Override
    public IPage<SchoolStudent> getList(StuParm parm) {
        IPage<SchoolStudent> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getList(page, parm);
    }

    @Transactional
    @Override
    public void addStu(SchoolStudent schoolStudent) {
        //保存学生信息
        int insert = this.baseMapper.insert(schoolStudent);
        //保存角色信息
        if (insert > 0) {
            StuRole stuRole = new StuRole();
            stuRole.setStuId(schoolStudent.getStuId());
            stuRole.setRoleId(schoolStudent.getRoleId());
            stuRoleService.save(stuRole);
        }
    }

    @Transactional
    @Override
    public void editStu(SchoolStudent schoolStudent) {
        //更新学生信息
        int i = this.baseMapper.updateById(schoolStudent);
        if (i > 0) {
            //更新角色信息
            QueryWrapper<StuRole> query = new QueryWrapper<>();
            query.lambda().eq(StuRole::getStuId, schoolStudent.getStuId());
            //先删除原来的
            stuRoleService.remove(query);
            //再插入新的
            StuRole stuRole = new StuRole();
            stuRole.setStuId(schoolStudent.getStuId());
            stuRole.setRoleId(schoolStudent.getRoleId());
            stuRoleService.save(stuRole);
        }
    }

    @Transactional
    @Override
    public void deleteStu(Long stuId) {
        int i = this.baseMapper.deleteById(stuId);
        if (i > 0) {
            //删除对应的角色信息
            QueryWrapper<StuRole> query = new QueryWrapper<>();
            query.lambda().eq(StuRole::getStuId, stuId);
            stuRoleService.remove(query);
        }
    }

    @Override
    public SchoolStudent getById(Long stuId) {
        return this.baseMapper.getById(stuId);
    }
}
